/**
 * 查询参数处理工具
 */

/**
 * 将对象转换为查询字符串
 * @param {Object} params - 查询参数对象
 * @returns {string} 查询字符串
 */
export function objectToQueryString(params) {
    if (!params || Object.keys(params).length === 0) {
        return "";
    }

    const queryString = new URLSearchParams();
    for (const [key, value] of Object.entries(params)) {
        if (value !== undefined && value !== null && value !== "") {
            queryString.append(key, value);
        }
    }

    return queryString.toString() ? `?${queryString.toString()}` : "";
}

/**
 * 从查询字符串解析对象
 * @param {string} queryString - 查询字符串
 * @returns {Object} 查询参数对象
 */
export function queryStringToObject(queryString) {
    if (!queryString) {
        return {};
    }
    // 移除开头的 '?' 字符
    const query = queryString.startsWith("?")
        ? queryString.substring(1)
        : queryString;

    if (!query) {
        return {};
    }

    const params = new URLSearchParams(query);
    const result = {};

    for (const [key, value] of params) {
        result[key] = value;
    }

    return result;
}

/**
 * 构造包含查询参数的完整路径
 * @param {string} path - 基础路径
 * @param {Object} query - 查询参数对象
 * @returns {string} 完整路径
 */
export function buildFullPath(path, query) {
    const queryString = objectToQueryString(query);
    return path + queryString;
}

export default {
    objectToQueryString,
    queryStringToObject,
    buildFullPath,
};
